package com.taptech.doufu.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.story.StoryDetailsActivity;
import com.taptech.doufu.ui.dialog.PermissionTipDialog;
import com.taptech.doufu.util.AppUtil2;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.HttpRequestUtil;
import com.taptech.doufu.util.ShareUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.constant.GlobalConfig;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.event.EventBusChangeVipState;
import com.taptech.doufu.event.EventBusCollectUnRead;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.ui.view.personalcenter.PersonalInviteWindow;
import com.taptech.doufu.util.ShareUtils;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.ui.view.ImageUtil;
import com.taptech.doufu.ui.view.SharePicPopupWindow;
import com.taptech.doufu.ui.view.SharePicPopupWindow2;
import com.taptech.doufu.ui.view.ShareTopPopupWindow;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;

public class BrowseActivity extends DiaobaoBaseActivity {

    final private int UPLOAD_FILE_RESULT = 100;
    static WebView webView;
    TextView title;
    private String url = "";
    private String mTitle;
    private String jsURL;
    private ImageView share;
    private String shareDes, shareUrl, shareTitle, imgUrl;
    private boolean initLogin = false;
    private LinearLayout mWaitProgressBarLayout;
    private static String shareCallBack;
    private static String doufu_payResult;

    private ValueCallback<Uri> mUploadMessage;

    // for Android Lolipop
    private ValueCallback<Uri[]> mFilePathCallback;

    private View topLayout;
    private final int REMOVE_TOP_FLAG = 4;
    private final int SHOW_TOP_FLAG = 5;
    private final int CLOSE_WEBVIEW = 6;
    private final int THIRD_PARTY_SHARE = 7;
    // ui数据
    private int screenWidth = 0;
    // ui控件
    View progressBar;


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        addShadeBg();
        setContentView(R.layout.activity_answer_star);
        // setTopTitleDrawable();
        topLayout = findViewById(R.id.activity_browse_top_layout);
        mWaitProgressBarLayout = (LinearLayout) findViewById(R.id.answer_wait_progressbar_layout);
        mWaitProgressBarLayout.setVisibility(View.GONE);
        webView = (WebView) findViewById(R.id.activity_answer_start_wb);
        title = (TextView) findViewById(R.id.activity_answer_start_title);
        share = (ImageView) findViewById(R.id.activity_answer_start_share);
        url = getIntent().getStringExtra(Constant.URL);
        url = Constant.changeUrlHost(url);
        //google渠道 、需要支付
        if (GlobalConfig.isGooglePlay && url.contains("needPay")) {
            initGooglePay();
        }
        boolean isOpenWebTest = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean("WEB_TEST_KEY", this, false);
        if (isOpenWebTest) {
            url = url.replace("https", "http");
        }
        mTitle = getIntent().getStringExtra(Constant.TITLE);
        jsURL = getIntent().getStringExtra(Constant.JS_URL);
        title.setText(mTitle);

        webView.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");
        webView.addJavascriptInterface(new JavascriptInterface(this), "native");
//        webView.setWebContentsDebuggingEnabled(true);
        // 初始化进度条
        screenWidth = ScreenUtil2.getScreenWidthPixel(this);
        progressBar = findViewById(R.id.webview_progress_bar);


        WebSettings webSettings = webView.getSettings();
        webSettings.setBuiltInZoomControls(true);   // 设置支持缩放
        webSettings.setJavaScriptEnabled(true);     //支持js
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);


     /*   webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);*/

        webSettings.setAppCacheMaxSize(1024 * 1024 * 8); // 在API18后，将自动控制
        webSettings.setAllowFileAccess(true);       // 设置允许访问文件数据
        webSettings.setAppCacheEnabled(true);       //APP内存使能
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();  //获取并设置app的内存地址
        webSettings.setAppCachePath(appCachePath);

        // “我来制作”上次图片的冲突
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
                if (!url.contains("weixin")) {
                    if (url.startsWith("http")){
                        webView.loadUrl(url);
                    }
                } else {
                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                TTLog.d("tag", "the progress bar is ========== finish");
                progressBar.setVisibility(View.GONE);
                // 页面加载完成后，隐藏waiting dialog
                if (mWaitProgressBarLayout != null && mWaitProgressBarLayout.getVisibility() == View.VISIBLE) {
                    mWaitProgressBarLayout.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(jsURL)) {
                    insertJs(jsURL);
                }


            }

            @Override
            public void onReceivedSslError(WebView view,SslErrorHandler handler, SslError error) {
                handler.cancel();
            }
        });
        webView.setWebChromeClient(new MyWebChromeClient(){

        });
        //Log.d("tag", "xxxx========" + url);
        // 保存cookie
        HttpRequestUtil.getCookie(this, url);
        webView.loadUrl(url);

        if (AccountService.getInstance().isLogin()) {
            initLogin = true;
        }
        // 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                startDownLoad(url);
            }
        });
    }

    private void insertJs(final String jsUrl) {
        webView.loadUrl("javascript:var script=document.createElement('script');script.src='"+jsUrl+"';document.head.appendChild(script);");
    }

//    InterstitialAD iad;

    // 打开默认浏览器开始下载
    private void startDownLoad(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    private class MyWebChromeClient extends WebChromeClient {


        public MyWebChromeClient() {
            super();
        }

        // For Android 3.0+
        public void downloadApp(JSONObject JsonObj) {
            TTLog.i("TAG", "downloadApp");
            AppUtil2.downLoadApp(BrowseActivity.this, AppUtil2.getExtreFromJsonObj(JsonObj));
            //startDownLoad(AppUtil2.getExtreFromJsonObj(JsonObj).getDl_url());
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            TTLog.d("tag", "click the android 2.0==================");
            if (mUploadMessage != null) {
                return;
            }
            mUploadMessage = uploadMsg;
            selectImage();
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            openFileChooser(uploadMsg, "");
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {

            TTLog.d("tag", "click the android 4.0==================");
            openFileChooser(uploadMsg, acceptType);
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            TTLog.d("tag", "click the android 5.0==================");
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;
            selectImage();
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            TTLog.d("tag", "the progress bar is ==========" + newProgress);
            displayWebViewProgressBar(newProgress);
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        webView.loadUrl("javascript:onRestart()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        webView.loadUrl("javascript:onStop()");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openCarcme();
                }else{
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AccountService.getInstance().isLogin() && initLogin == false) {
            HttpRequestUtil.getCookie(this, url);
            webView.loadUrl(url);
            initLogin = true;
        }
        if (SharePicPopupWindow.qq_share_type == 107) {// qq
            if (webView != null && shareCallBack != null) {
                webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + "QQ" + "'})");
            }
            SharePicPopupWindow.qq_share_type = 0;
        } else if (SharePicPopupWindow.qq_share_type == 108) {// qzone
            if (webView != null && shareCallBack != null) {
                webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + "QZone" + "'})");
            }
            SharePicPopupWindow.qq_share_type = 0;
        }

        if (result != null && totalMsg != null && !totalMsg.equals("")) {
            TTLog.i("TAG", "totalMsg:" + totalMsg);
            if (result.equals("success")) {
                callBack(success);
            } else if (result.equals("cancel")) {
                callBack(cancel);
            } else// if (result.equals("fail") || result.equals("invalid"))
            {
                callBack(fail);
            }
        }
    }

    public void backOnclick(View view) {
        finish();
    }


    public void googlePlayPay(String pId,int optionId) {
        if (GlobalConfig.isGooglePlay) {
            googlePay(pId,optionId);
        }
    }


    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }


        @android.webkit.JavascriptInterface
        public void changeTitle(String titleName) {
            TTLog.s("xxxx========" + titleName);
            Message msg = new Message();
            msg.what = 1;
            msg.obj = titleName;
            mHandler.sendMessage(msg);

        }


        @android.webkit.JavascriptInterface
        public void login() {
            //清除
            EventBusCollectUnRead.clearUnRead();
            AccountService.getInstance().clearAccount();
            AccountService.getInstance().setAccountBack(true);
            AccountService.getInstance().jumpToLogin();
        }

        @android.webkit.JavascriptInterface
        public void unregister(){
            //清除
            EventBusCollectUnRead.clearUnRead();
            AccountService.getInstance().clearAccount();
            AccountService.getInstance().setAccountBack(true);
            Toast.makeText(context,"账号已注销",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(context, MainHomeActivity.class);
            startActivity(intent);
            finish();
        }


        /**
         * type=1 ：分享我们，2：成绩，3：排行榜
         */

        @android.webkit.JavascriptInterface
        public void share(String type, String des, String url) {

//            String desc = "我正在 豆花阅读 App 看《"+topicBean.getTitle()+"》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! "+topicBean.getShareUrl();
//            ShareUtil.Companion.shareText(context,"豆花阅读",des+url);

            shareDes = des;
            shareUrl = url;
            Message msg = new Message();
            msg.what = 2;
            msg.obj = type;
            mHandler.sendMessage(msg);
            TTLog.s("type==" + type);
            TTLog.s("des==" + des);
            TTLog.s("url==" + url);
        }

        /**
         * type=1 ：分享我们，2：成绩，3：排行榜
         */

        @android.webkit.JavascriptInterface
        public void shareGameTitle(String type, String des, String url, String title) {

//            String desc = "我正在 豆花阅读 App 看《"+topicBean.getTitle()+"》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! "+topicBean.getShareUrl();
//            ShareUtil.Companion.shareText(context,title,des+url);
            shareTitle = title;
            shareDes = des;
            shareUrl = url;
            Message msg = new Message();
            msg.what = 2;
            msg.obj = type;
            mHandler.sendMessage(msg);
            TTLog.s("type==" + type);
            TTLog.s("des==" + des);
            TTLog.s("url==" + url);
        }


        @android.webkit.JavascriptInterface
        public void richShare(String des, String url, String title, String img, String callback) {

//            String desc = "我正在 豆花阅读 App 看《"+topicBean.getTitle()+"》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! "+topicBean.getShareUrl();
//            ShareUtil.Companion.shareText(context,title,des+url);
            shareTitle = title;
            shareDes = des;
            shareUrl = url;
            imgUrl = img;
            shareCallBack = callback;
            Message msg = new Message();
            msg.what = 2;
            msg.obj = 2;
            mHandler.sendMessage(msg);
            TTLog.s("des==" + des);
            TTLog.s("url==" + url);
        }



        /**
         * 隐藏分享按钮
         */

        @android.webkit.JavascriptInterface
        public void notShareView() {
            mHandler.sendEmptyMessage(3);
        }


        @android.webkit.JavascriptInterface
        public void invite() {
            String desc = "我正在 豆花 App 看小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! http://"+Constant.HOST_END_PAST;
            ShareUtil.Companion.shareText(context,"豆花",desc);
            new PersonalInviteWindow(BrowseActivity.this, 0, null);
        }


        @android.webkit.JavascriptInterface
        public void removeTopView() {
            mHandler.sendEmptyMessage(REMOVE_TOP_FLAG);
        }


        @android.webkit.JavascriptInterface
        public void showTopView() {
            mHandler.sendEmptyMessage(SHOW_TOP_FLAG);
        }


        @android.webkit.JavascriptInterface
        public void closeWebview() {
            mHandler.sendEmptyMessage(CLOSE_WEBVIEW);
        }

        @android.webkit.JavascriptInterface
        public void openWeexPage(String url) {
            SimpleWeexActivity.startActivity(BrowseActivity.this,url);
        }

        @android.webkit.JavascriptInterface
        public void openWeexPage(String url,String data) {
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(data);
            SimpleWeexActivity.startActivity(BrowseActivity.this,jsonObject,url);
        }


        @android.webkit.JavascriptInterface
        public void getUserIdFromNative(){
            webView.loadUrl("javascript:getUserId('"+AccountService.getInstance().getUserUid()+"')");
        }


        @android.webkit.JavascriptInterface
        public void loadRewardVideoAd(){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showVideoAd();
                }
            });
        }


        @android.webkit.JavascriptInterface
        public boolean isGooglePlay(){
            return GlobalConfig.isGooglePlay;
        }

        @android.webkit.JavascriptInterface
        public void googlePay(String pId,int optionId) {
            googlePlayPay(pId,optionId);
        }

        /**
         * 调用应用下载
         */
        @android.webkit.JavascriptInterface
        public void downloadApp(String JsonObj) {
            AppUtil2.downLoadApp(BrowseActivity.this, AppUtil2.stringConvertToObject(JsonObj));
        }

        /**
         * 打开链接
         */
        @android.webkit.JavascriptInterface
        public void openUrl(String url) {

            startDownLoad(url);
        }

        /**
         * 跳转到广场
         */
        @android.webkit.JavascriptInterface
        public void goToSquare() {
            Intent intent = new Intent();
            intent.setClass(BrowseActivity.this, SquareActivity.class);
            startActivity(intent);
        }

        /**
         * 跳转到首页
         * @param param  参数字典  目前仅有一个参数 index == 0,1,2,3,4 分别对应首页的5个卡片，
         */
        @android.webkit.JavascriptInterface
        public void jumpToHomePage(String param){
            com.alibaba.fastjson.JSONObject json = JSON.parseObject(param);
            int index = json.getInteger("index");
            Intent intent = new Intent(BrowseActivity.this, MainHomeActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }

        /**
         * 打开app
         */
        @android.webkit.JavascriptInterface
        public void openApp(String pkg_name) {
            AppUtil2.openApp(BrowseActivity.this, pkg_name);
        }

        /**
         * 检查APP是否已经安装app
         */
        @android.webkit.JavascriptInterface
        public boolean isAppInstalled(String pkg_name) {
            return AppUtil2.isApplicationAvilible(BrowseActivity.this, pkg_name);
        }

        @android.webkit.JavascriptInterface
        public void thirdPartyShare(String data) {
            Message msg = new Message();
            msg.what = THIRD_PARTY_SHARE;
            msg.obj = data;
            mHandler.sendMessage(msg);
        }


        @android.webkit.JavascriptInterface
        public void jumpToSingle(int id) {
            StoryDetailsActivity.Companion.startActivity(getThisActivity(),id);
        }


        /**
         * 调用支付
         */
        @android.webkit.JavascriptInterface
        public void doufuPay(String jsonData) {

        }

        @android.webkit.JavascriptInterface
        public void jumpToUser(String uid) {
            if (AccountService.getInstance().isLogin() && uid != null) {
                if (!AccountService.getInstance().isUserSelf(uid)) {
                    PersonalInfoService.enterOthersPersonalCenter(BrowseActivity.this, uid);
                }
            } else {
                AccountService.getInstance().jumpToLogin();
            }
        }

        /**
         * 我要投稿
         */
        @android.webkit.JavascriptInterface
        public void jumpToDeliverComics() {
            //投稿页面也是h5页面
        }

        @android.webkit.JavascriptInterface
        public void toast(String content) {
            UIUtil.toastMessage(BrowseActivity.this, content);
        }

        @android.webkit.JavascriptInterface
        public void jumpToArticleDes(String id, int object_type) {
            Intent intent = null;
            switch (object_type) {
                case Constant.OBJECT_TYPE_NOVEL:
                    NovelDetailsActivity.Companion.startActivity(BrowseActivity.this,id);
                    break;
                case Constant.OBJECT_TYPE_DRAW:
                    intent = new Intent(BrowseActivity.this, NewPersonalNoteDesActivity.class);
                    intent.putExtra(Constant.ARTICLE_ID, id);
                    intent.putExtra(Constant.OBJECT_TYPE, String.valueOf(object_type));
                    BrowseActivity.this.startActivity(intent);
                    break;
                case Constant.OBJECT_TYPE_CARTOON:
                    SimpleWeexActivity.startActivity(context,"TFNovel/TFComicDetail.js?id="+id,null);
                    break;
            }
        }

    }


    private void showVideoAd() {
        webView.loadUrl("javascript:showAdFail()");

    }



    String success;
    String cancel;
    String fail;


    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null != msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null != msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(BrowseActivity.this);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", null);
        builder.create().show();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (msg.obj != null) {
                        title.setText(msg.obj.toString());
                    }
                    break;
                case 2:
                    if (msg.obj != null) {
                        if ("1".equals(msg.obj.toString())) {
                            SharePicPopupWindow popupWindow = new SharePicPopupWindow(BrowseActivity.this);
                            ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.OWN_SHARE_FLAG);
                            popupWindow.setShareBeans(shareInfo);
                            // 显示窗口
                            popupWindow.showAtLocation(share, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                        } else if ("2".equals(msg.obj.toString())) {
                            if ((shareUrl != null) && (shareUrl.length() > 10)) {
                                SharePicPopupWindow2 popupWindow = new SharePicPopupWindow2(BrowseActivity.this);
                                ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG);
                                shareInfo.setShartText(shareTitle);
                                shareInfo.setTitle(shareTitle);
                                shareInfo.setDescription(shareDes);
                                shareInfo.setShareUrl(shareUrl);
                                shareInfo.setImagUrl(imgUrl);
                                popupWindow.setShareBeans(shareInfo);
                                // 显示窗口
                                popupWindow.showAtLocation(share, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                            } else {
                                SharePicPopupWindow popupWindow = new SharePicPopupWindow(BrowseActivity.this);
                                ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG);
                                shareInfo.setShartText(shareTitle);
                                shareInfo.setTitle(shareTitle);
                                shareInfo.setDescription(shareDes);
                                shareInfo.setShareUrl(shareUrl);
                                shareInfo.setImagUrl(imgUrl);
                                popupWindow.setShareBeans(shareInfo);
                                // 显示窗口
                                popupWindow.showAtLocation(share, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                            }

                        } else if ("3".equals(msg.obj.toString())) {
                            share.setVisibility(View.VISIBLE);

                        }
                    }
                    break;
                case 3:
                    share.setVisibility(View.GONE);
                case REMOVE_TOP_FLAG:
                    topLayout.setVisibility(View.GONE);
                    break;
                case SHOW_TOP_FLAG:
                    topLayout.setVisibility(View.VISIBLE);
                    break;
                case CLOSE_WEBVIEW:
                    backOnclick(null);
                    break;

                case THIRD_PARTY_SHARE:
                    if (msg.obj != null) {
                        String data = msg.obj.toString();
                        ShareUtils.thirdPartyShare(BrowseActivity.this,data,false);
                    }
                    break;
                default:
                    break;
            }

        }

        ;
    };

    public void shareOnlick(View view) {
        // TODO Auto-generated method stub
        TTLog.s(shareDes + "===shareDes===shareUrl===" + shareUrl);
        ShareTopPopupWindow popupWindow = new ShareTopPopupWindow(BrowseActivity.this);
        ShareBeansInfo shareInfo = new ShareBeansInfo(shareDes, shareUrl, ShareBeansInfo.RANK_SORCE_SHARE_FLAG);
        popupWindow.setShareBeans(shareInfo);
        // 显示窗口
        popupWindow.showAsDropDown(view, 0, 0); // 设置layout在PopupWindow中显示的位置
    }

    String totalMsg;
    String result;

    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see {@link Activity#onActivityResult}
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

//        if (WeiboService.getInstance().mSsoHandler != null) {
//            WeiboService.getInstance().mSsoHandler.authorizeCallBack(requestCode, resultCode, intent);
//        }
        String sharePath = "";
        switch (resultCode) {
            case 666:
                sharePath = "sina_weibo";
                break;
            case 999:
                sharePath = "tecent_weibo";
                break;
            default:
                break;
        }
        if (!sharePath.equals("")) {
            webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + sharePath + "'})");
        }
        // webview上传图片

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Uri[] results = null;
            if (requestCode == REQ_CAMERA) {
                afterOpenCamera();
                if (cameraUri != null) {
                    String dataString = cameraUri.toString();
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                } else {
                    results = null;
                }


            } else if (requestCode == REQ_CHOOSE && intent != null) {
                String dataString = intent.getDataString();
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
            if (results != null) {
                mFilePathCallback.onReceiveValue(results);
            }
            mFilePathCallback = null;
        } else {
            if (null == mUploadMessage)
                return;
            Uri uri = null;
            if (requestCode == REQ_CAMERA) {
                afterOpenCamera();
                if (cameraUri != null) {
                    uri = cameraUri;
                } else {
                    uri = null;
                }
            } else if (requestCode == REQ_CHOOSE) {
                uri = afterChosePic(intent);
            }
            if (mUploadMessage != null) {

                mUploadMessage.onReceiveValue(uri);
                mUploadMessage = null;
            }
        }

    }

    private void callBack(final String string) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //调用JS中的 函数，当然也可以不传参
                //webView.loadData("", "text/html", "UTF-8");
                webView.loadUrl("javascript:" + string + "('" + totalMsg + "')");
            }
        });
    }

    public final boolean checkSDcard() {
        boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (!flag) {
            Toast.makeText(this, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
        }
        return flag;
    }

    protected final void selectImage() {
        if (!checkSDcard())
            return;
        String[] selectPicTypeStr = {"拍照", "相册"};

        AlertDialog dialog = new AlertDialog.Builder(this).setItems(selectPicTypeStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    // 相机拍摄
                    case 0:
                        if(ContextCompat.checkSelfPermission(BrowseActivity.this, Manifest.
                                permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                            PermissionTipDialog dialog1 = new PermissionTipDialog(BrowseActivity.this);
                            dialog1.show();
                            dialog1.setPre("相册权限");
                            dialog1.setOnBtnClickListener(() -> {
                                ActivityCompat.requestPermissions(BrowseActivity.this, new
                                        String[]{ Manifest.permission.CAMERA}, 1);
                            });
                        }else {
                            openCarcme();
                        }
                        break;
                    // 手机相册
                    case 1:
                        chosePic();
                        break;
                    default:
                        break;
                }
                compressPath = Environment.getExternalStorageDirectory().getPath() + "/fuiou_wmp/temp";
                new File(compressPath).mkdirs();
                compressPath = compressPath + File.separator + "compress.jpg";
            }
        }).show();

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                }
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                    mFilePathCallback = null;
                }
            }
        });
    }

    String imagePaths;
    Uri cameraUri;
    String compressPath = "";
    private final static int FILECHOOSER_RESULTCODE = 1;
    private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE + 1;
    private static final int REQ_CHOOSE = REQ_CAMERA + 1;

    /**
     * 打开照相机
     */
    private void openCarcme() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        imagePaths = Environment.getExternalStorageDirectory().getPath() + "/fuiou_wmp/temp/" + (System.currentTimeMillis() + ".jpg");
        // 必须确保文件夹路径存在，否则拍照后无法完成回调
        File vFile = new File(imagePaths);

        cameraUri = FileProvider.getUriForFile(
                this,
                getPackageName() + ".fileprovider",
                vFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        startActivityForResult(intent, REQ_CAMERA);
    }

    /**
     * 拍照结束后
     */
    private void afterOpenCamera() {
        try {
            File f = new File(imagePaths);

            if (f.exists()) {
                addImageGallery(f);
            } else {
                cameraUri = null;
            }

            File newFile = ImageUtil.compressFile(f.getPath(), compressPath);
        } catch (Exception e) {

        }
    }

    /**
     * 解决拍照后在相册中找不到的问题
     */
    private void addImageGallery(File file) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    /**
     * 本地相册选择图片
     */
    private void chosePic() {

        ImageUtil.delFile(compressPath);
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
        String IMAGE_UNSPECIFIED = "image/*";
        innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
        Intent wrapperIntent = Intent.createChooser(innerIntent, "选择图片");
        startActivityForResult(wrapperIntent, REQ_CHOOSE);

    }

    /**
     * 选择照片后结束
     *
     * @param data
     */
    private Uri afterChosePic(Intent data) {

        Uri result = null;
        if (data != null) {
            result = data.getData();
        }
        return result;
    }

    public static void sendCallbackTojs(String sharePath) {
        if (!sharePath.equals("") && webView != null && shareCallBack != null) {
            webView.loadUrl("javascript:" + shareCallBack + "({'channel':'" + sharePath + "'})");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (!TextUtils.isEmpty(url) && "http://api.doufu.douhuayuedu.com/index.php/journal/detail?id=405".equals(url)) {
            EventBusChangeVipState event = new EventBusChangeVipState();
            event.setTag(EventBusChangeVipState.TAG_CHANGE_VIPSTATE);
            EventBus.getDefault().post(event);
        }
        mHandler.sendEmptyMessage(CLOSE_WEBVIEW);
        super.onDestroy();

    }

    /**
     * 展示进度条进度
     *
     * @param rate
     */
    private void displayWebViewProgressBar(int rate) {
        if (!progressBar.isShown() && rate > 0 && rate < 100) {
            progressBar.setVisibility(View.VISIBLE);
        }
        int progressWidth = (int) (rate / 100.0 * screenWidth);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) progressBar.getLayoutParams();
        layoutParams.width = progressWidth;
        progressBar.setLayoutParams(layoutParams);

    }


    public static void startActivity(Context context,String url) {
        Intent intent = new Intent();
        intent.setClass(context, BrowseActivity.class);
        intent.putExtra(Constant.URL, url);
        context.startActivity(intent);
    }
}
